package com.example.srm.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.srm.auth.anno.Authority;
import com.example.srm.auth.mapper.TUserMapper;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.domain.TPermission;
import com.example.srm.domain.TUser;
import com.example.srm.domain.tree.Tree;
import com.example.srm.domain.vo.Result;
import com.example.srm.auth.service.TPermissionService;
import com.example.srm.auth.service.TUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author pfk
 * @creatTime 2021/11/24 18:18
 * @describe    权限操作
 */
@RestController
@RequestMapping("/permission")
@CrossOrigin
public class PermissionController {

    @Autowired
    private TUserService userService;
    @Autowired
    private TPermissionService permissionService;
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取当前用户的权限code
     * @return
     */
    @GetMapping("/per_code")
    public Result getCurrentPermission(HttpServletRequest request){
        //获取token
        String token = request.getHeader(PermissionConstant.AUTH_TOKEN);
        //根据token查询用户
        TUser user = userService.getUserByToken(token);
        //根据用户查询权限
        List<Tree> codes = userService.getPermissionById(user.getId());
        return new Result().setData(codes).setSuccess(true);
    }

    /**
     * 查询权限树
     * @return
     */
    @GetMapping("/tree")
    @Authority(auth = "account:permission:list")
    public Result findPermissionTree(){
        //判断用户是否有权限查询权限树
        List<Tree> permissionTree = permissionService.findPermissionTree();
        System.out.println(permissionTree);
        return new Result().setData(permissionTree).setSuccess(true);
    }


    /**
     * 添加权限
     * @return
     */
    @PostMapping("")
    @Authority(auth = "account:permission:add")
    public Result save(@RequestBody TPermission permissionView) throws Exception {
        if (permissionView.getType() == null || permissionView.getCode()==null || permissionView.getName() == null){
            return new Result().setMsg("参数不合法");
        }
        // 先判断再同一个父节点下面是不是有同名或者同code的权限 如果有就不允许添加
        TPermission permission = permissionService.getOne(
                new QueryWrapper<TPermission>().nested(query->query
                                                    .eq(PermissionConstant.name,permissionView.getName())
                                                    .or()
                                                    .eq(PermissionConstant.code,permissionView.getCode()))
                                                .eq(PermissionConstant.parentId,permissionView.getParentId()));
        if (permission!=null){
            return new Result().setMsg("该节点下已经有同名 或者 同code 的权限");
        }
        boolean save = permissionService.save(permissionView);
        return new Result().setSuccess(save).setMsg("添加成功");
    }

    /**
     * 删除权限
     * @param id
     * @return
     */
    @DeleteMapping(value = "",params = {"id"})
    @Authority(auth = "account:permission:delete")
    public Result delete(String id){
        return new Result().setSuccess(permissionService.removeById(id));
    }

    /**
     * 根据id获取权限
     * @param id
     * @return
     */
    @GetMapping(value = "",params = {"id"})
    @RequiresPermissions("account:user:list")
    public Result findById(String id){
        TPermission permission = permissionService.getById(id);
        return new Result().setData(permission).setSuccess(true);
    }

    /**
     * 修改权限
     * @param permissionView
     * @return
     * @throws Exception
     */
    @Authority(auth = "account:permission:update")
    @PutMapping("")
    public Result update(@RequestBody TPermission permissionView) throws Exception {
        if (permissionView.getType() == null || permissionView.getCode()==null || permissionView.getName() == null){
            return new Result().setMsg("参数不合法");
        }
        //  修改权限的时候验证 规则就是统一父id下 除了本id外没有 重复的name 和code
        int count = permissionService.count(new QueryWrapper<TPermission>()
                .nested(query->query
                        .eq(PermissionConstant.name,permissionView.getName())
                        .eq(PermissionConstant.code,permissionView.getCode()))
                .ne(PermissionConstant.id,permissionView.getId()));
        if(count !=0){ return new Result().setMsg("该节点下已经有同名 或者 同code 的权限"); }
        boolean update = permissionService.updateById(permissionView);
        //更新redis中的用户权限
        boolean update2  =userService.updatePermissionForRedis(permissionView.getId());

        return new Result().setSuccess(update);
    }


}
